//#define _CRTDBG_MAP_ALLOC
#include "StdAfx.h"
#include "StoppingVehicleDetection.h"
#include <time.h>
#include <direct.h>

StoppingVehicleDetection::StoppingVehicleDetection(char* ipAddress,IplImage* image)
{ 
    previousSavedFrame=0;

    previousRegion=0;
    currentRegion = 0;

    prevoiusComp_rect=cvRect(0,0,0,0);
    currentComp_rect=cvRect(0,0,0,0);		

    prevoiusPoint= cvPoint(0,0);
    currentPoint= cvPoint(0,0);

    lastBoxPoint=cvPoint(image->width/2, image->height);
    lastSavedPoint= cvPoint(0,0);
    saved = false;

    check=false;
    vehicleCount=0;
    
    this->ipAddress=ipAddress;
    

    mkdir(this->ipAddress);
    
    sprintf(fileName,"%s\\output.txt",this->ipAddress);
    //strcpy(fileName,this->ipAddress.c_str());
    //strcat(fileName,this->ipAddress.c_str());
    //strcat(fileName,"\\output.txt");
    //char buf[80];
    //sprintf(fileName,"output\\%s.txt",this->ipAddress);
   /* strcpy(fileName,"output\\");
    strcat(fileName,this->ipAddress.c_str());
    strcat(fileName,".txt");*/

    outPutFile.open (fileName, ios::out);
    
   // printf("%s\n",fileName);
    //outPutFile.open ("output\\output.txt", ios::out);
	outPutFile.close();
}
void StoppingVehicleDetection::setCurrentRegion(Frame* currentFrame,CvRect currentComp_rect,CvScalar color)
{
    this->currentFrame=currentFrame=currentFrame;
    //if the angle >240 and <300
    currentPoint = cvPoint((currentComp_rect.x + currentComp_rect.width/2),(currentComp_rect.y + currentComp_rect.height/2));

    int xDiff = abs(currentPoint.x-prevoiusPoint.x);
    int yDiff = currentPoint.y-prevoiusPoint.y;
    int imageHeight=currentFrame->getFrameSize().height;
    if(xDiff>0&&yDiff>0&&currentPoint.y>0.25*imageHeight&&currentPoint.y<0.60*imageHeight)
    {
        if(xDiff<5&&yDiff<5)
		{
		    cvReleaseImage(&currentRegion);
			cvSetImageROI( this->currentFrame->getFrame(), currentComp_rect );
			currentRegion = cvCloneImage(this->currentFrame->getFrame());
			cvResetImageROI( this->currentFrame->getFrame());
			
			cvReleaseImage(&previousRegion);
		    previousRegion = cvCloneImage(currentRegion);
		    prevoiusComp_rect=currentComp_rect;
			check=true;
		}		       
    }
     cvRectangle(this->currentFrame->getFrame(),cvPoint(currentComp_rect.x,currentComp_rect.y),cvPoint(currentComp_rect.x+ currentComp_rect.width,currentComp_rect.y+ currentComp_rect.height), color,1,8,0);
     
     prevoiusPoint = currentPoint;
}

void StoppingVehicleDetection::detectAndSave()
{
    char outputFileName[80];
    sprintf(outputFileName,"output.txt");
    ofstream outPutFile;
    
    
    if(check&&previousRegion!=0&&prevoiusComp_rect.width!=0&&prevoiusComp_rect.height!=0)  
    {
        cvSetImageROI( this->currentFrame->getFrame(), prevoiusComp_rect );
		IplImage* currentFrameTemp = cvCloneImage(this->currentFrame->getFrame());
		cvResetImageROI( this->currentFrame->getFrame());
		
		OpticalFlow* opticalFlow = new OpticalFlow();
		//double opFlowAve =opticalFlow->calculateOpticalFlowAverage(currentFrameTemp,previousRegion);
		outPutFile.open (outputFileName, ios::app);
		time_t start = clock();
		
		
		//double opFlowAve =opticalFlow->calculateOpticalFlowAverageGPU(currentFrameTemp,previousRegion);
		double opFlowAve =opticalFlow->calculateHSOpticalFlowAverage(currentFrameTemp,previousRegion);
		
		time_t end=clock();
        outPutFile<<"OPFGPU, "<<(end - start) / (double)CLOCKS_PER_SEC<<", ";
        outPutFile.close();
		
		//double opFlowAve=drawOptFlowMap(flow, cflow, 1, 1.5, CV_RGB(0, 255, 0)); //step was 16
		
		if(prevoiusPoint.y<lastBoxPoint.y)
		{
		    saved=false;			    
		    //lastBoxPoint = prevoiusPoint;
		}
		else
		{
		     /*outPutFile.open ("output\\output.txt", ios::app);
             outPutFile<<"SKIPPED, Saved and moving forward"<<endl;
             outPutFile.close();*/
		}
		
        if(opFlowAve<1) // was 1
        {
            if(saved&&prevoiusPoint.y>=lastBoxPoint.y)
            {   
                /*  delete previousSavedFrame;						
                previousSavedFrame=previousRegionFrame; // used to find the stopped object*/

                //outPutFile.open ("output\\output.txt", ios::app);
                outPutFile.open (fileName, ios::app);
                outPutFile<<endl<<"SKIPPED, Saved, Moving Forward"<<endl;
                outPutFile.close();
            }
            
            if(!saved)  // backed objects are going to duplicate with a warnning
            {
                Frame* previousRegionFrame = new Frame();
                previousRegionFrame->setFrame(cvCloneImage(previousRegion));
                previousRegionFrame->setFrameNo(this->currentFrame->getFrameNo());
                previousRegionFrame->getHistogram();
                
                if(previousSavedFrame!=0)
                {
                    SURFeatures* surf = new SURFeatures();						 

                    //IplImage* object_gray = cvCreateImage(cvSize(previousRegion->width,previousRegion->height), 8, 1);
                    IplImage* object_gray = cvCreateImage(cvGetSize(previousRegion), 8, 1);
                    cvCvtColor( previousRegion, object_gray, CV_BGR2GRAY );
                    surf->setObject(object_gray);
                 // surf->extractSURFGPU(0);
                    surf->setSrcCorners();
                    surf->extractSURF(0);


                       // previousRegion->width,previousRegion->height
                    IplImage* image_gray = cvCreateImage(cvGetSize(previousSavedFrame->getFrame()), 8, 1);
                    //IplImage* image_gray = cvCreateImage(cvSize(previousSavedFrame->getFrame()->width,previousSavedFrame->getFrame()->height), 8, 1);

                    cvCvtColor( previousSavedFrame->getFrame(), image_gray, CV_BGR2GRAY );

                    surf->setImage(image_gray);
                    //surf->extractSURFGPU(1);
                    surf->extractSURF(1);
                    
               
                   if( surf->locatePlanarObject())
                    {
                        for(int i = 0; i < 4; i++ )
                        {
                            /*CvPoint r1 = dst_corners[i%4];
                            CvPoint r2 = dst_corners[(i+1)%4];
                            cvLine( correspond, cvPoint(r1.x, r1.y+object->height ),
                            cvPoint(r2.x, r2.y+object->height ), colors[8] );*/ 
                        }
                    }

                    vector<int> ptpairs;

                    surf->flannFindPairs( ptpairs );
                    
                    char buf[50];
                    //sprintf(buf, "output\\surfOB%d__%d.jpg", vehicleCount,surf->getObjectDescriptors()->total);
                    sprintf(buf, "%s\\surfOB%d__%d.jpg", this->ipAddress,vehicleCount,surf->getObjectDescriptors()->total);
                    cvSaveImage(buf,previousRegion,0);

                    //sprintf(buf, "output\\surfIM%d__%d.jpg", vehicleCount,surf->getImageDescriptors()->total);
                    sprintf(buf, "%s\\surfIM%d__%d.jpg",this->ipAddress, vehicleCount,surf->getImageDescriptors()->total);
                    cvSaveImage(buf,previousSavedFrame->getFrame(),0);

                    float pairsObjectRatio=(float)ptpairs.size()/surf->getObjectDescriptors()->total;
                    outPutFile.open (fileName, ios::app);
                    //outPutFile.open ("output\\output.txt", ios::app);
                    
                    
                  //  cout<<"ObjKp"<<surf->getObjectKeyPointsGpuMat().cols<<"ObjDes"<<surf->getObjectDescriptorsGpuMat().cols<<endl;
//cout<<"ObjKp"<<surf->getImageKeyPointsGpuMat().cols<<"ObjDes"<<surf->getImageDescriptorsGpuMat().cols<<endl;
                    
                  //  float pairsObjectRatio=0.5;
                    if(pairsObjectRatio<0.8&&pairsObjectRatio>0.3) // was 2
                    {
                        outPutFile<<"Possibility of Duplicate "<<endl;	
                    }
                    else if(pairsObjectRatio>0.3)
                    {
                        outPutFile<<"SKIPPED, Very HIGH Possibility of Duplicate "<<endl;	
                        saved=true;
                    }

                   // outPutFile<<endl<<"No of ptpairs: "<<ptpairs.size()<<" Object Descriptors: "<<surf->getObjectDescriptors()->total<<" Image Descriptors: "<<surf->getImageDescriptors()->total<<"Reatio :"<<pairsObjectRatio<<endl;
                    outPutFile.close();
                

                    cvReleaseImage(&object_gray);
                    cvReleaseImage(&image_gray);
                    
                    delete surf;
                }
                delete previousSavedFrame;						
			    previousSavedFrame=previousRegionFrame; // used to find the stopped object
                
            }
            
            if(!saved)
            {
                time_t rawtime;
                struct tm * timeinfo;

                time ( &rawtime );
                timeinfo = localtime ( &rawtime );
                //printf ( "Current local time and date: %s", asctime (timeinfo) );


                vehicleCount++;
                char buf[80];
                //sprintf(buf, "output\\%s.jpg", asctime(timeinfo));
                
               // strftime (buf,80,"output\\%d-%m-%Y_%H.%M.%S.jpg",timeinfo);
                strftime (buf,80,"\\%d-%m-%Y_%H.%M.%S.jpg",timeinfo);
                //strftime (buf,80,"output\\%d-%m-%Y_%X.jpg",timeinfo);
                //strftime (buf,80,"%I%M%p.jpg",timeinfo);
                // puts (buf);

                 char bufFull[100];
                sprintf(bufFull,"%s%s",this->ipAddress,buf);
               // printf(bufFull,"%s");
                puts(bufFull);
                cvSaveImage(bufFull,this->currentFrame->getFrame(),0);
                //cvSaveImage(buf,previousRegion,0);
                saved=true;
                //cvShowImage("Previous Region",previousRegion);
				cvShowImage("Detected Vehicle",previousRegion);
                lastSavedPoint = prevoiusPoint;
                //lastBoxPoint = prevoiusPoint;                        
            }
            
        }
        lastBoxPoint = prevoiusPoint;
        
        //outPutFile.open ("output\\output.txt", ios::app);
        outPutFile.open (fileName, ios::app);
		outPutFile<<"X: "<<currentPoint.x<<" Y: "<<currentPoint.y<<" Width: "<<prevoiusComp_rect.width<<" Height: "<<prevoiusComp_rect.height<<" PreAve: "<<previousOpFlowAve<<" OpFlowAve: "<<opFlowAve<<" VCount: "<<vehicleCount<<endl;
		outPutFile.close();
		
		previousOpFlowAve=opFlowAve;
		
		
		
		
		
		
		cvReleaseImage(&currentFrameTemp);
		check=false;
        
        delete opticalFlow;
    }

}

StoppingVehicleDetection::~StoppingVehicleDetection(void)
{
    // delete currentFrame;
  //  cvReleaseImage(&motionImage);
    cvReleaseImage(&previousRegion);
    cvReleaseImage(&currentRegion);

	delete previousSavedFrame;
    
}